package com.sinszm.wechat.service.impl;

import com.sinszm.common.exception.ApiException;
import com.sinszm.wechat.configuration.WxProperties;
import com.sinszm.wechat.dao.DbWeChatAppRelRepository;
import com.sinszm.wechat.dao.DbWeChatCommonRepository;
import com.sinszm.wechat.dao.entity.DbWeChatAppRel;
import com.sinszm.wechat.dao.entity.DbWeChatCommon;
import com.sinszm.wechat.dao.entity.support.Module;
import com.sinszm.wechat.service.InitService;
import com.sinszm.wechat.service.support.UserInitReqDto;
import com.sinszm.wechat.service.support.WechatInfoDto;
import com.sinszm.wechat.util.BasicUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 初始化
 * @author chenjianbo
 * @date 2020-3-8
 */
@Service
public class InitServiceImpl implements InitService {

    @Resource
    private DbWeChatCommonRepository dbWeChatCommonRepository;

    @Resource
    private DbWeChatAppRelRepository dbWeChatAppRelRepository;

    @Resource
    private WxProperties wxProperties;

    /**
     * 验证授权
     * @param arg0  账号
     * @param arg1  授权码
     */
    private void validate(String arg0, String arg1) {
        if (StringUtils.isEmpty(arg0) || StringUtils.isEmpty(arg1)) {
            throw new ApiException("ERR-01", "授权参数不能为空");
        }
        if (!wxProperties.getAccount().equals(arg0)) {
            throw new ApiException("ERR-01", "访问账号不匹配");
        }
        if (!wxProperties.getSecret().equals(arg1)) {
            throw new ApiException("ERR-01", "访问授权码不匹配");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void createWechatInfo(WechatInfoDto dto, String admin, String adminSecret) {
        validate(admin, adminSecret);
        if (dto == null) {
            throw new ApiException("ERR-02", "参数不能为空");
        }
        String appId = dto.getAppId();
        if (StringUtils.isEmpty(appId)) {
            throw new ApiException("ERR-03", "APPID不能为空");
        }
        String secret = dto.getAppSecret();
        if (StringUtils.isEmpty(secret)) {
            throw new ApiException("ERR-04", "APPSECRET不能为空");
        }
        String domain = dto.getDomain();
        if (StringUtils.isEmpty(domain)) {
            throw new ApiException("ERR-05", "DOMAIN域名不能为空");
        }
        domain = domain.replace("http://","")
                .replace("https://","")
                .replace("/","");
        DbWeChatCommon common = new DbWeChatCommon();
        common.setId(BasicUtils.uuid());
        common.setAppId(appId);
        common.setAppSecret(secret);
        common.setAuthDomain(domain);
        common.setBusinessDomain(domain);
        common.setJsDomain(domain);
        common.setMsgToken("");
        common.setMsgUrl("");
        common.setCreateTime(new Date());
        dbWeChatCommonRepository.save(common);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Object createUserInfo(UserInitReqDto dto, String admin, String adminSecret) {
        validate(admin, adminSecret);
        if (dto == null) {
            throw new ApiException("ERR-02", "参数不能为空");
        }
        String appId = dto.getAppId();
        if (StringUtils.isEmpty(appId)) {
            throw new ApiException("ERR-03", "APPID不能为空");
        }
        DbWeChatCommon common = dbWeChatCommonRepository.getByAppId(appId);
        if (common == null) {
            throw new ApiException("ERR-04", "APP未初始化配置");
        }
        String redirectAddress = dto.getRedirectAddress();
        if (StringUtils.isEmpty(redirectAddress)) {
            throw new ApiException("ERR-05", "用户未设置回调地址");
        }
        Module module = dto.getModule() == null ? Module.BASE : dto.getModule();
        //验证自动生成的账号有效性
        boolean state = true;
        String userId = BasicUtils.getOneTimePassword();
        do {
            long n = dbWeChatAppRelRepository.countByUserId(userId);
            if (n > 0) {
                userId = BasicUtils.getOneTimePassword();
            } else {
                state = false;
            }
        }while (state);
        //保存数据
        DbWeChatAppRel rel = new DbWeChatAppRel();
        rel.setId(BasicUtils.uuid());
        rel.setAppId(appId);
        rel.setModule(module);
        rel.setCreateTime(new Date());
        rel.setRedirectAddress(redirectAddress);
        rel.setUserId(userId);
        rel.setUserSecret(BasicUtils.uuid());
        dbWeChatAppRelRepository.save(rel);
        //返回值
        Map<String, String> map = new HashMap<>(0);
        map.put("account", rel.getUserId());
        map.put("secret", rel.getUserSecret());
        return map;
    }

}
